<template>
  <a-drawer :visible="visible" :title="title" @close="closeDrawer" width="450">
    <div style="padding-bottom: 100px">
      <a-form layout="vertical">

        <a-form-item label="营业执照" name="business_license"
                     v-bind="validateInfos.business_license">
          <a-upload
              :action="$utils.imgAction"
              :headers="{ 'org-token': $store.getters.token }"
              :multiple="false"
              v-model:file-list="photoList"
              @change="uploadPhoto"
              name="image"
              :data="{ dir: 'org_village_user' }"
              accept="image/jpg,image/jpeg,image/gif,image/png"
              list-type="picture-card"
          >
            <div v-if="photoList.length < 1">
              <PlusOutlined/>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="公司名称" name="name" v-bind="validateInfos.name">
          <a-input v-model:value="modelRef.name" placeHolder="请输入公司名称"/>
        </a-form-item>
        <a-form-item label="所在地" name="place" v-bind="validateInfos.area">
          <a-cascader
              v-model:value="modelRef.area"
              :options="areaOptions"
              placeholder="请选择所在地"
              change-on-select
              :load-data="loadAreaData"
              @change="areaChange"
          />
        </a-form-item>
        <a-form-item label="税号" name="tax_Id" v-bind="validateInfos.tax_id">
          <a-input v-model:value="modelRef.tax_id" placeHolder="请输入税号"/>
        </a-form-item>
        <a-form-item label="开户行" name="bank" v-bind="validateInfos.opening_bank">
          <a-input v-model:value="modelRef.opening_bank" placeHolder="请输入开户行"/>
        </a-form-item>
        <a-form-item label="收款账号" name="account" v-bind="validateInfos.receiving_account">
          <a-input v-model:value="modelRef.receiving_account" placeHolder="请输入收款账号"/>
        </a-form-item>
        <a-form-item label="负责人" name="head_name" v-bind="validateInfos.head_name">
          <a-input v-model:value="modelRef.head_name" placeHolder="请输入负责人"/>
        </a-form-item>
        <a-form-item label="负责人号码" name="head_phone" v-bind="validateInfos.head_phone">
          <a-input v-model:value="modelRef.head_phone" placeHolder="请输入负责人号码"/>
        </a-form-item>
        <a-form-item label="绑定项目" name="village_id" v-bind="validateInfos.village_id"
                     v-if="(modelRef.head_phone&&modelRef.head_name)">
          <a-select
              v-model:value="modelRef.village_id"
              :options="optionsBuild"
              mode="multiple"
              placeholder="请选择项目"
          ></a-select>
          <template v-if="modelRef.head_name&&modelRef.head_phone&&!modelRef.village_id" #extra>
            <span style="color: red;font-size: 14px">请选择项目</span>
          </template>
        </a-form-item>

        <a-form-item label="是否签订合作协议">
          <a-radio-group v-model:value="modelRef.is_sign">
            <a-radio :value="1">已签署</a-radio>
            <a-radio :value="0">未签署</a-radio>
          </a-radio-group>
        </a-form-item>

        <template v-if="modelRef.is_sign==1">
          <a-form-item label="协议文件">
            <a-upload
                :action="$utils.fileAction"
                :multiple="false"
                :headers="{ 'org-token': $store.getters.token }"
                v-model:file-list="fileList"
                name="file"
                :max-count="9"
                accept=".doc,.docx,.pdf,.jpg,.jpeg,.png"
                @change="handleUploadChange"
            >
              <a-button>
                <upload-outlined></upload-outlined>
                上传
              </a-button>
            </a-upload>
          </a-form-item>
          <a-form-item label="协议签订日" v-bind="validateInfos.sign_date">
            <a-date-picker style="width: 100%" placeholder="请选择协议签订日"
                           v-model:value="modelRef.sign_date"
                           :valueFormat="dateFormatStr"/>
          </a-form-item>
          <a-form-item v-bind="validateInfos.expire_date">
            <template #label>
              协议到期日
              <a-tooltip>
                <template #title> 若填写，则过期后 渠道人员将无法绑定该公司，适合必须绑定协议的公司选择。
                </template>
                <question-circle-outlined class="ml-5"/>
              </a-tooltip>
            </template>
            <a-date-picker style="width: 100%" placeholder="请选择协议到期日"
                           v-model:value="modelRef.expire_date"
                           :valueFormat="dateFormatStr"/>
          </a-form-item>
        </template>

      </a-form>
      <div class="drawer-footer">
        <a-space>
          <a-button @click="closeDrawer">取消</a-button>
          <a-button type="primary" @click="onSave">保存</a-button>
        </a-space>
      </div>
    </div>
  </a-drawer>
</template>

<script>
import {ref, reactive, watch, toRefs} from "vue"
import {Form, message, Modal} from "ant-design-vue"
import {PlusOutlined, QuestionCircleOutlined, UploadOutlined} from "@ant-design/icons-vue";
import request from "@/common/utils/request";
import utils from "@/common/utils/utils";
import {area} from '@antv/g2plot'
import dayjs from 'dayjs'
import store from '@/store'

const dateFormatStr = "YYYY-MM-DD"
const useForm = Form.useForm
export default {
  methods: {area},
  components: {PlusOutlined, UploadOutlined, QuestionCircleOutlined},
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    id: {
      type: Number,
      default: 0
    }
  },
  setup(props, context) {
    const state = reactive({
      title: "新增渠道公司",
      detail: undefined,
      photoList: [],

    })
    const fileList = ref([])
    const modelRef = reactive({
      name: "",
      area: [],
      address: undefined,
      tax_id: "",
      opening_bank: "",
      village_id: [],
      receiving_account: "",
      is_sign: 1,
      head_name: "",
      head_phone: "",
      sign_date: undefined,
      expire_date: undefined,
      business_license: []
    })
    const area = ref([]);
    const ruleRef = reactive({
      business_license: [{
        required: false,
        message: '请上传营业执照'
      }],
      name: [{
        required: true,
        message: '请输入公司名称'
      }],
      area: [
        {
          required: false,
          // validator: (rules, value) => areaValidator(value),
          trigger: "blur",
        },
      ],
      tax_id: [{
        required: false,
        message: '请输入税号'
      }],
      opening_bank: [{
        required: false,
        message: '请输入开户行'
      }],
      receiving_account: [{
        required: false,
        message: '请输入收款账号'
      }],
      sign_date: [{
        required: false,
        message: '请选择签署日期'
      }],
      expire_date: [{
        required: false,
        message: '请选择到期日期'
      }],
      head_name: [{
        required: true,
        message: '请输入负责人'
      }],
      head_phone: [{
        required: true,
        message: '请输入负责人号码'
      }],
    })

    const lincenceValidator = async (value) => {

      if (!value.length) {
        return Promise.reject("营业执照为必填项");
      }
      return Promise.resolve();
    };

    watch(() => modelRef.is_sign, (val) => {
      const sign = val == 1
      ruleRef.sign_date = [{
        required: sign,
        message: '请选择签署日期'
      }]
      // ruleRef.expire_date = [{
      //   required: false,
      //   message: '请选择到期日期'
      // }]
    })

    const {resetFields, validate, validateInfos} = useForm(modelRef, ruleRef)

    const commitSave = () => {

      if (modelRef.head_phone && modelRef.head_name && !modelRef.village_id) {
        return
      }
      modelRef.address = areas;
      const params = {
        ...modelRef
      }
      if (modelRef.is_sign == 0) {
        delete params.sign_date
        delete params.expire_date
      }
      if (fileList.value.length) {
        params.protocol_file = fileList.value.map(item => {
          return {
            url: item.url,
            name: item.name
          };
        })
      }

      if (props.id) {
        params.id = props.id
        console.log(params, "编辑参数")
        request.put("/org", "/business/customer/channel/channelCompanyEdit", params).then(res => {
          message.success("操作成功")
          context.emit("onCommit")
        })
      } else {
        console.log(params, "新建参数")
        request.post("/org", "/business/customer/channel/channelCompanyAdd", params).then(res => {
          message.success("操作成功")
          context.emit("onCommit")
        })
      }
    }

    const onSave = () => {
      validate().then(() => {

        if (props.id) {
          if (modelRef.head_phone != state.detail?.head_phone && state.detail.head_phone?.length) {
            utils.modalConfirm({
              content: `渠道公司负责人号码已修改，修改后原负责人手机号码将不再是负责人，确定要修改吗？`,
              centered: true,
              onOk: () => {
                commitSave()
              },
            });
          } else {
            commitSave()
          }
        } else {
          commitSave()
        }


      })
    }


    // 营业执照照片
    const getBusinessLicense = (imageUrl) => {
      request
          .post("/third", "/wxapp/tool/cvOcr/bizlicense", {
            file: imageUrl,
            failNoMsg: true,
          })
          .then((res) => {
            if (res.result) {
              modelRef.tax_id = res.result.reg_num;
              modelRef.name = res.result.enterprise_name;
            }
          });
    };


    const uploadPhoto = (info) => {
      let resFileList = [...info.fileList];
      let result = resFileList.slice(-1);
      result = result[0];
      if (result && result.response) {
        if (result.response.code == 1000) {
          modelRef.business_license = [
            {
              url: result.response.data.fileUrl,
              name: result.response.data.fileName
            }
          ];
          getBusinessLicense(result.response.data.fileUrl);
          state.photoList = resFileList;
        } else {
          message.warning(result.response.msg);
        }
      }
    };


    // 所属城市区域
    const areaOptions = ref([]);
    let areas = {
      provinceId: "",
      provinceName: "",
      cityId: "",
      cityName: "",
      districtId: "",
      districtName: "",
      streetId: "",
      streetName: "",
    };
    const areaChange = (areaChangeValue, value) => {
      if (value) {
        areas.provinceId = value[0]?.value;
        areas.provinceName = value[0]?.label;
        areas.cityId = value[1]?.value;
        areas.cityName = value[1]?.label;
        areas.districtId = value[2]?.value;
        areas.districtName = value[2]?.label;
        areas.streetId = value[3]?.value;
        areas.streetName = value[3]?.label;
      } else {
        Object.keys(areas).forEach((key) => {
          areas[key] = "";
        });
      }
    };
    // 加载已选择列表
    // 省
    const getArea = () => {
      utils.getAreaOptions(1, {}, false).then((list) => {
        areaOptions.value = list;
      });
    };

    // 动态加载省市区信息
    const loadAreaData = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true; // load options lazily
      if (targetOption.level < 4) {
        utils
            .getAreaOptions(targetOption.level + 1, {
              id: targetOption.value,
              leafLevel: 4,
            }, false)
            .then((res) => {
              if (res.length) {
                targetOption.children = res;
              } else {
                targetOption.isLeaf = true;
              }
              targetOption.loading = false;
            });
      }
    };


    const getDetail = () => {
      console.log("获取详情")
      request.get("/org", "/business/customer/channel/channelCompanyDetail", {id: props.id}).then(res => {
        console.log(res)
        state.detail = res.data
        for (let key in modelRef) {
          modelRef[key] = state.detail[key]
        }
        modelRef.village_id = state.detail.village_id ? state.detail.village_id : undefined

        state.photoList = modelRef.business_license
        if (res?.data?.protocol_file) {
          fileList.value = res.data.protocol_file;
        }
        //省市区
        const {provinceId, cityId, districtId, streetId} = state.detail.address;
        areas = state.detail.address;
        if (provinceId) {
          area.value.push(provinceId);
          utils.getAreaOptions(1, {}, false).then((list) => {
            areaOptions.value = list;
            let index = list.findIndex((item) => item.value == provinceId);
            if (cityId && index > -1) {
              area.value.push(cityId);
              let province = areaOptions.value[index];
              utils.getAreaOptions(2, {id: provinceId}, false).then((cityList) => {
                if (cityList.length) {
                  province.children = cityList;
                  index = cityList.findIndex((item) => item.value == cityId);
                  if (districtId && index > -1) {
                    area.value.push(districtId);
                    let city = province.children[index];
                    utils
                        .getAreaOptions(3, {id: cityId}, false)
                        .then((districtList) => {
                          if (districtList.length) {
                            city.children = districtList;
                            index = districtList.findIndex(
                                (item) => item.value == districtId
                            );
                            if (streetId && index > -1) {
                              area.value.push(streetId);
                              let district = city.children[index];
                              utils
                                  .getAreaOptions(4, {id: districtId}, false)
                                  .then((streetList) => {
                                    if (streetList.length) {
                                      district.children = streetList;
                                      index = streetList.findIndex(
                                          (item) => item.value == streetId
                                      );
                                    } else {
                                      district.isLeaf = true;
                                    }
                                  });
                            }
                          } else {
                            city.isLeaf = true;
                          }
                        });
                  }
                } else {
                  province.isLeaf = true;
                }
              });
            }
          });
        }
        modelRef.area = area.value;

      })
    }

    // 意向项目
    const optionsBuild = ref([]);
    const getVillageList = () => {
      request.get("/org", "/build/villageAndBuildList/v2", {}).then((res) => {
        let vList = [];
        res.villageList.forEach((item) => {
          vList.push({
            label: item.name,
            value: item.id,
          });
        });
        optionsBuild.value = vList;
      });
    };


    const init = () => {
      state.title = props.id == 0 ? "新增渠道公司" : "编辑渠道公司"
      if (props.id != 0) {
        getDetail()
      }
      getArea()
      getVillageList();
    }

    watch(() => props.visible, (val) => {
      if (val == true) {
        init()
      } else {
        resetFields()
        areaOptions.value = [];
        state.detail = {};
        area.value = [];
        fileList.value = [];
        state.photoList = [];

      }
    })

    const closeDrawer = () => {
      context.emit("toClose")
    }


    //上传文件
    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList = resFileList.slice(-1);
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });
      }
    };


    return {
      ...toRefs(state),
      closeDrawer,
      validateInfos,
      modelRef,
      onSave,
      loadAreaData,
      areaChange,
      areaOptions,
      area,
      dateFormatStr,
      handleUploadChange,
      fileList,
      uploadPhoto,
      optionsBuild


    }
  }
}
</script>

<style lang="less" scoped>
:deep(.ant-form-item) {
  margin-bottom: 10px;
}
</style>